package com.qs.imp;

import java.sql.Connection; 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.qs.dao.ConnectionManager;
import com.qs.entity.MoonInfo;
import com.qs.entity.UserFriend;

import com.qs.inter.UserFriendInt;

public class UserFriendImp implements UserFriendInt {
	Connection conn;
	PreparedStatement ps;
	ResultSet rs;
	
	public int countNews(int friendUserId) throws Exception {
		int countNews = 0;
		String sql = "select count(MoonId) from MoonInfo where UserId=?";
		conn =ConnectionManager.getConnction();
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, friendUserId);
			rs = ps.executeQuery();
			rs.next();
			countNews = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return countNews;
	}

	
	public List sUserFriendMessage(UserFriend userfriend) throws Exception {
		List list = new ArrayList<UserFriend>();
		String sql = "select * from UserFriend where UserName=?";
		conn = ConnectionManager.getConnction();
		ps = conn.prepareStatement(sql);
		ps.setString(1, userfriend.getUserName());
		rs = ps.executeQuery();
		
		while(rs.next()){
			UserFriend userfriend1 = new UserFriend();
			userfriend1.setUserId(rs.getInt("UserId"));
			userfriend1.setFriendLoginName(rs.getString("FriendLoginName"));
			userfriend1.setUserName(rs.getString("UserName"));
			list.add(userfriend1);
		}
		
		return list;
	}


	public List sUserFriendMoon(int friendUserId, int pageSize, int pageNow) throws Exception {
		List list = new ArrayList<UserFriend>();
		String sql = "select top " +pageSize+ " * from MoonInfo where UserId = ? and " +
				" MoonId not in (select top "+(pageSize*pageNow-pageSize)+" MoonId from MoonInfo where UserId = ?)";
//		System.out.println(sql);
		conn = ConnectionManager.getConnction();
		ps = conn.prepareStatement(sql);
		ps.setInt(1, friendUserId);
		ps.setInt(2, friendUserId);
		rs = ps.executeQuery();
		while(rs.next()){
			MoonInfo mooninfo = new MoonInfo();
			mooninfo.setUserId(rs.getInt("UserId"));
			mooninfo.setMoon(rs.getString("Moon"));
			mooninfo.setMoonId(rs.getInt("MoonId"));
			list.add(mooninfo);
		}
		return list;
	}


	public int sUserFriendId(UserFriend userfriend) throws Exception {
		String sql = "select UserId from UserMessage where LoginName=?";
		conn = ConnectionManager.getConnction();
		ps = conn.prepareStatement(sql);
		ps.setString(1, userfriend.getFriendLoginName());
		rs = ps.executeQuery();
		if(rs.next()){
			ActionContext.getContext().getSession().put("FRIENDID", rs.getInt("UserId"));
			return 1;
		}
		return 0;
	}

}
